// pages/publish/index.js
import { host, apiUrl } from '../../config';
const app = getApp();
let token = null;

Page({
  data:{
    localIds: [],
    serverIds: [],
    message: '',
    picture: false,
    voice: false,
    topicList: [{
    topic_name: '全部',
    topic_cate_id: 0
  }],
  topic: 0
  },
  onLoad(options){
    token = app.globalData.token;
    this.getTopic();
  },
  getTopic() {
    wx.request({
      url: apiUrl + '/topic',
      method: 'GET',
      header: {
        Authorization: token
      },
      success: (res) => {
        this.setData({
          topicList: this.data.topicList.concat(res.data.data)
        })
      },
      fail: (err) => {
        console.log(err);
      }
    })
  },
  // 选择话题
  switchTopic(e) {
    console.log(e);
    this.setData({
      topic: e.target.dataset.topicid
    });
  },
  handlePicture() {
    wx.chooseImage({
      count: (9 - this.data.localIds.length), // 默认9
      success: (res) => {
        var tempFilePaths = this.data.localIds.concat(res.tempFilePaths);
        this.setData({
          localIds: tempFilePaths.slice(-9),
          picture: true
        });
        const i = 0;
        this.uploadPhotos(res.tempFilePaths, i);
      },
      fail: (err) => {
        if (err.errMsg == 'chooseImage:fail cancel') {
          if (!this.data.localIds.length) {
            this.setData({ post_type: 0 });
          }
        } else {
          wx.showModal({
            title: '提示',
            message: '相机选择器模块载入错误',
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
              }
            }
          })
        }
        console.log(err);
      },
      complete: () => {
        if (!this.data.localIds.length) {
          this.setData({ picture: false });
        }
      }
    })
  },// 上传照片
  uploadPhotos(e, i) {
    const photosIds = e;
    let count = i;
    console.log('上传图片到服务器');
    wx.uploadFile({
      url: host + '/c-api/upload-file',
      filePath: photosIds[i],
      name: 'image',
      header: {
        Authorization: token
      },
      success: (result) => {
        console.log('上传成功');
        console.log(result);
        const res = JSON.parse(result.data).data;
        count++;
        if (count < photosIds.length) {
          this.uploadPhotos(e, count);
        }
        const tmp = this
          .data
          .serverIds
          .concat([res.filename]);
        this.setData({
          serverIds: tmp.slice(-9)
        });
      },
      fail: (err) => {
        console.log('上传失败');
        console.log(err);
        wx.showModal({
          title: '提示',
          content: '上传图片失败',
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              this.setData({
                localIds: [],
                serverIds: [],
                post_type: 0,
                picture: false
              })
            }
          }
        })
      }
    });
  },
  // 删除选中图片
  removeEleFromArray(arr, key) {
    const source = arr;
    for (let i = 0; i < source.length; i++) {
      if (source[i] === key) {
        source.splice(i, 1);
        break;
      }
    }
    return source;
  },
  handleRemovePicture(event) {
    console.log(event);
    const tmp = this.data.localIds;
    const key = event.currentTarget.dataset.img;
    const idx = event.currentTarget.dataset.key;
    const afterArray = this.removeEleFromArray(tmp, key);
    let tmp2 = this.data.serverIds.slice(-9);
    let temp3 = tmp2.splice(idx, 1); // 坑爹
    this.setData({ localIds: afterArray, serverIds: tmp2 });
    if (afterArray.length <= 0) {
      this.setData({ post_type: 0, picture: false });
    }
  },
  setMessage(e) {
    this.setData({
      message: e.detail.value
    })
  },
  handleSubmit() {
    const {
      picture,
      voice,
      serverIds,
      message,
      topic
    } = this.data;
    if (!(!!message.length || voice || picture)) {
      return ;
    }
    wx.showLoading({
      title: '发布中...',
    });
    let data;

    if (voice) {
      data = {
        message: message.length ? message : '分享语音',
        topic_id: topic,
        post_type: 3
      };
    } else if (picture) {
      data = {
        mediaList: serverIds,
        topic_id: topic,
        post_type: 2,
        message: message.length
          ? message
          : '分享图片'
      };
    } else {
      data = {
        message: message,
        post_type: 0,
        mediaList: [],
        topic_id: topic
      };
    }
    wx.request({
      url: apiUrl + '/post',
      header: {
        Authorization: token
      },
      method: 'POST',
      data,
      success: (res) => {
        wx.hideLoading()
        if (res.data.code === 1) {
          wx.showToast({
            title: '发表成功',
            icon: 'success',
            duration: 1500
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1000);
        } else {
          wx.showModal({
            content: res.data.msg,
            confirmText: '知道了',
            showCancel: false
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showModal({
          content: '发表失败',
          confirmText: '知道了',
          showCancel: false
        });
      }
    });
  }
})
